package com.atguigu.securitydemo1.controller;

import com.atguigu.securitydemo1.entity.Users;
import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PostFilter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PreFilter;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jungle
 * @create 2022-10-07 19:46
 */
@RestController
@RequestMapping("/test")
public class TestController {


    @GetMapping("/hello")
    public String add() {
        return "hello security";
    }

    @GetMapping("/index")
    public String index() {
        return "hello index";
    }


    @GetMapping("/update")
    //@Secured({"ROLE_sale","ROLE_manager"})
    //@PreAuthorize("hasAnyAuthority('admins')")
    @PostAuthorize("hasAnyAuthority('admins')")
    public String update() {
        System.out.println("update.....");
        return "hello update";
    }

    /**
     * 返回结果是
     * new Users(2L, "admin2", "888")
     */
    @GetMapping("getAll")
    @PostAuthorize("hasAnyAuthority('admins')")
    @PostFilter("filterObject.username == 'admin2'")
    public List<Users> getAllUser() {
        ArrayList<Users> list = new ArrayList<>();
        list.add(new Users(1L, "admin1", "6666"));
        list.add(new Users(2L, "admin2", "888"));
        System.out.println(list);
        return list;
    }

    /**
     * 1、进入控制器之前对数据进行过滤
     */
    @GetMapping("getTestPreFilter")
    @PreAuthorize("hasRole('ROLE_sale')")
    @PreFilter(value = "filterObject.id%2==0")
    public List<Users> getTestPreFilter(@RequestBody List<Users> list) {
        list.forEach(t -> {
            System.out.println(t.getId() + "\t" + t.getUsername());
        });
        return list;
    }
}
